<!-- src/components/Selector/deptSelectTree.vue -->
<template>
	<a-tree-select
		v-model:value="selectedValue"
		class="xn-wd"
		:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
		placeholder="请选择组织"
		allow-clear
		tree-default-expand-all
		:tree-data="treeData"
		:tree-default-expanded-keys="treeDefaultExpandedKeys"
		:field-names="{
			children: 'children',
			label: 'name',
			value: 'id'
		}"
		@change="handleChange"
	/>
</template>

<script setup>
	import { onMounted, ref } from 'vue'
	import bizUserApi from '@/api/biz/bizUserApi'

	// 定义组件的属性
	const props = defineProps({
		modelValue: {
			type: String,
			default: undefined
		}
	})

	// 定义组件的事件
	const emit = defineEmits(['update:modelValue'])

	// 数据定义
	const treeData = ref([])
	const treeDefaultExpandedKeys = ref([])
	const selectedValue = ref(props.modelValue)

	// 监听外部值的变化
	watch(
		() => props.modelValue,
		(newVal) => {
			selectedValue.value = newVal
		}
	)

	// 获取组织树数据
	const loadOrgTree = () => {
		bizUserApi.userOrgTreeSelector().then((res) => {
			if (res !== null) {
				treeData.value = res
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						treeDefaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								treeDefaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		})
	}

	// 处理选择变化
	const handleChange = (value) => {
		emit('update:modelValue', value)
	}

	// 组件挂载时加载数据
	onMounted(() => {
		loadOrgTree()
	})

	// 暴露方法给父组件
	defineExpose({
		refresh: loadOrgTree
	})
</script>

<style scoped>
	.xn-wd {
		width: 100%;
	}
</style>
